import 	Sqlite from "@/library/sqlite/sqlite.main.js";
/**
 * 
 * @description 网络恢复后自动上传数据文件
 *
 * @param {*} tableName  需要上传的数据表名  
 */
async function AutoUploadOnlie(tableName){
	   
	   var souces = [];//数据源
	   var res;
	   var idx = 0;
	   
	   //读取数据库
	   let sqliteRes = await ReadDatabase(tableName);
	   if(sqliteRes){
		   console.log("sqliteRes",sqliteRes);
		   souces = sqliteRes;
	   }
	   if(souces.length<=0)return;
	   //显示进度
	   var showLoading = plus.nativeUI.showWaiting("开始上传", {back: "none"});//{back: "none"}用来禁止返回键
	    for(var item of souces){
			idx++
		    res = await DefaultUpload();
			console.log(res);
			//上传成功
			{
				// showLoading.setTitle(`正在上传${idx / souces.length}`);
				showLoading.setTitle(`正在上传 ${idx} / ${souces.length}`);
				Sqlite.DeleteTableRow(tableName,item.id);//上传成功后删除数据表中记录
			}
			//上传失败
			{
				
			}
			
		}
		
		setTimeout(()=>{
			showLoading.close();
			uni.showToast({
			    icon:'none',
				title:"上传成功"
			})
		},600);
	   
	
}
//获取数据库数据
/**
 * @param {*} tableName 数据表名称
 */
async function ReadDatabase(tableName){
	return new Promise(async (resolve,reject)=>{
		//是否打开
		if(Sqlite.IsOpen()){
			let isTable = await Sqlite.QueryIsTable("test");
			console.log("是否是数据表:"+isTable);
			if(!isTable)return;
			
			Sqlite.SelectDataList("test")
			.then(e=>{
				resolve(e);
			})
			.catch(e=>{
				console.log(e);
				resolve([]);
			});
		}else{
			let isOpen = await Sqlite.OpenSqlite();
			if(isOpen){
				let isTable = await Sqlite.QueryIsTable("test");
				console.log("是否是数据表:"+isTable);
				if(!isTable)return;
				
				Sqlite.SelectDataList("test")
				.then(e=>{
					resolve(e);
				})
				.catch(e=>{
					console.log(e);
					resolve([]);
				});
			}else{
				resolve([])
			}
		}
	});
}

//模拟上传
function DefaultUpload(){
	return new Promise((resolve,reject)=>{
		setTimeout(()=>{
			resolve({isOk:true});
		},1000)
	})
}
export default AutoUploadOnlie;